package util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author 李东喜
 * 2009-9-3
 */
public class TreeUtils {


    @SuppressWarnings("unchecked")
    public static <K> Map<K, List<Map<String, Object>>> group(Map<String, Object>[] maps, String parent, Class<K> clazz) {
        Map<K, List<Map<String, Object>>> group = new HashMap<K, List<Map<String, Object>>>(0);
        for (Map<String, Object> m : maps) {
            K key = (K) m.get(parent);
            List<Map<String, Object>> list = group.get(key);
            if (null != list) {
                list.add(m);
            } else {
                list = new ArrayList<Map<String,Object>>(0);
                list.add(m);
                group.put(key, list);
            }
        }
        return group;
    }
    
    public static void d() {
        /*Map<Integer, List<Map<String, Object>>> m = group(null, "", Integer.class);
        List<Map<String, Object>> root = m.get("ROOT");
        set(root, m, "ID");
        output(root, "list");*/
    }
    
    public static <K> void set(List<Map<String, Object>> parents, Map<K, List<Map<String, Object>>> group, String parentId, Class<K> clazz) {
        for (Map<String, Object> parent : parents) {
            List<Map<String, Object>> o = group.get((K) parent.get(parentId));
            if (null != o) {
                for (Map<String, Object> map : o) {
                    System.out.println(map);
                }
                parent.put("list", o);
                set(o.subList(0, 1), group, parentId, clazz);
            }
            break;
        }
    }
    
    @SuppressWarnings("unchecked")
    public static void output(List<Map<String, Object>> list, String key, String... names) {
        for (Map<String, Object> m : list) {
            Object o = m.get(key);
            if (null != o) {
                output((List<Map<String, Object>>) o, key);
            } else {
                for (String name : names) {
                    System.out.println(m.get(name));
                }
            }
        }
    }
    
}
